const fs = require('fs'); 
const path = require("path")
const { app } = require("electron");
const Router = require('koa-router') 
const router = new Router()


var all = { list:[], search:[],docs:[],info:"", }
let filepath = path.join( app.getPath("userData") ,'copy-link.json');

router.get('/api/item', async function(ctx, next) {
    ctx.body = {  data: all.list }
})

router.post('/api/item', async function(ctx, next) {
    let { body } = ctx.request 
    console.log(body) 
    let { list } = all
    if(body.id){
        list.splice(list.findIndex(e => e.id == body.id ), 1, body)
    }else{
        body.id = Date.now()
        list.push(body)
    } 
    all.list = list
    ctx.body = {  code:0, msg: 'ok' }
})

router.del('/api/item', async function(ctx, next) {
    let { body } = ctx.request 
    let { list } = all 
    list.splice(list.findIndex(e => e.id == body.id ), 1)
    all.list = list
    ctx.body = {  code:0, msg: 'ok' }
})


router.get('/api/search', async function(ctx, next) {
    ctx.body = {  data: all.search }
})
 
router.post('/api/search', async function(ctx, next) {
    let { body } = ctx.request 
    let { search } = all  
    if(!search.includes(body.search)) search.push(body.search)
    all.search = search
    ctx.body = {  code:0, msg: 'ok' }
})

router.del('/api/search', async function(ctx, next) {
    let { body  } = ctx.request 
    let { search } = all
    search.splice(search.findIndex(item => body.search ), 1)
    all.search = search
    ctx.body = {  code:0, msg: 'ok' }
})


router.all('/api/save', async function(ctx, next) {
    fs.writeFileSync(filepath,JSON.stringify(all))
    ctx.body = {  code:0, msg: 'ok' }
})

router.all("/api/info", async function (ctx, next) {
    let { info } = ctx.request.body;
    if(info){
        all.info = info || all.info  
    }else{
      fs.writeFileSync(filepath, JSON.stringify(all));
    }
    ctx.body = { all };
  });

module.exports = router
 